<template>
  <el-card>
    <el-row align="middle" type="flex" style="height:50px">
      <el-button size="small" type="info" @click="$router.push('/test')">去考试</el-button>
      <el-button size="small" type="primary" @click="addQuestion">新增考题</el-button>
      <el-button size="small" type="success" @click="exportQuestion">导出考题</el-button>
      <UploadExcel title="导入考题" :on-success="importData" />

    </el-row>
    <!-- 导出excel -->
    <el-table border stripe="" :data="list" height="380" @row-click="clickRow">
      <el-table-column label="#" type="index" align="center" width="50px" />
      <el-table-column label="题目" prop="title" />
      <el-table-column label="答案" prop="answer" align="center" width="100px" />
      <el-table-column label="类型" align="center" width="100px" prop="type" :formatter="formatType" />
      <el-table-column label="难度" align="center" width="100px" prop="diff" :formatter="formatDiff" />

      <el-table-column align="center" label="操作" fixed="right" width="120px">
        <template slot-scope="{ row }">
          <el-button type="text" size="small" @click="editQuestion(row.id)">编辑</el-button>
          <el-button type="text" size="small" @click="delQuestion(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 从表 -->
    <el-table border stripe="" :data="currentFromList" style="margin-top:10px">
      <el-table-column header-align="center" label="选项名" prop="name" width="100px" align="center" />
      <el-table-column header-align="center" label="选项值" prop="item" />
    </el-table>
    <el-dialog title="编辑试题" :visible.sync="showDialog">
      <el-form ref="answerForm" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="answer">
          <el-select v-model="formData.diff">
            <el-option v-for="item in diffList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入名称" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="选项A" prop="A">
          <el-input v-model="formData.A" placeholder="请输入选项A" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="选项B" prop="B">
          <el-input v-model="formData.B" placeholder="请输入选项B" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="选项C" prop="C">
          <el-input v-model="formData.C" placeholder="请输入选项C" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="选项D" prop="D">
          <el-input v-model="formData.D" placeholder="请输入选项D" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item v-for="(item,index) in formItems" :key="index" :label="`选项${item}`" prop="D">
          <el-input v-model="formData[item]" :placeholder="`请输入选项${item}`" type="textarea" :rows="2" />
        </el-form-item>

        <el-form-item>
          <el-button type="text" @click="addItem">添加选项</el-button>
          <el-button type="text" @click="removeItem">移除选项</el-button>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="formData.answer" placeholder="请输入答案" @keyup.enter.native="btnOK" />
        </el-form-item>

      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="8">
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog title="导入数据" :visible="showImportDialog">
      <el-form label-width="120px">
        <el-form-item label="excel起始的行数">
          <el-input-number v-model="importNumber" :min="1" :max="100" label="数据行起始的行数" />
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="8">
          <el-button size="small" type="primary" @click="btnImportOK">确定</el-button>
          <el-button size="small" @click="btnImportCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </el-card>
</template>

<script>
import { export_json_to_excel } from '@/vendor/Export2Excel'
import UploadExcel from '@/components/UploadExcel'
const headers = {
  '题型': 'type',
  '难度': 'diff',
  '题干': 'title',
  '选项': 'items',
  '参考答案': 'answer',
  '答案解析': 'none',
  '评分标准': 'none',
  '题目备注': 'none'

}
export default {
  components: {
    UploadExcel
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('questions') || '[]'),
      fromList: JSON.parse(localStorage.getItem('fromlist') || '[]'),
      showDialog: false,
      showImportDialog: false, // 显示弹层的对话框
      importResult: null, // 导入的数据
      importNumber: 2,
      currentId: null,
      formItems: [],
      formData: {
        title: '',
        A: '',
        B: '',
        C: '',
        D: '',
        answer: '',
        type: '2',
        diff: '3'
      },
      typeList: [{ id: '1', name: '单选题' }, { id: '2', name: '多选题' }, { id: '3', name: '判断题' }, { id: '4', name: '简答题' }],
      diffList: [{ id: '1', name: '1星' }, { id: '2', name: '2星' }, { id: '3', name: '3星' }, { id: '4', name: '4星' }, { id: '5', name: '5星' }],
      rules: {
        title: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        A: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        B: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        C: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        D: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        answer: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    currentFromList() {
      return this.fromList.filter(item => item.fid === this.currentId)
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem('questions', JSON.stringify(this.list))
      }
    },
    fromList: {
      deep: true,
      handler() {
        localStorage.setItem('fromlist', JSON.stringify(this.fromList))
      }

    }
  },
  created() {
    if (this.list.length) {
      this.currentId = this.list[0].id
    }
  },
  methods: {
    // 添加选项
    addItem() {
      const arr = 'efghijklmn'.toUpperCase().split('')
      this.formItems.push(arr[this.formItems.length])
    },
    removeItem() {
      this.formItems.pop()
    },
    // 导入数据
    importData(results) {
      this.importResult = results
      this.showImportDialog = true
    },
    addQuestion() {
      this.showDialog = true
    },
    clickRow(row) {
      this.currentId = row.id
    },
    get_uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4'
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
      s[8] = s[13] = s[18] = s[23] = '-'

      var uuid = s.join('')
      return uuid
    },
    editQuestion(id) {
      this.formData = this.list.find(item => item.id === id)
      this.formItems = this.fromList.filter(item => item.fid === id).slice(4).map(item => item.name)
      this.showDialog = true
    },
    delQuestion(id) {
      this.$confirm('确认删除该试题吗').then(() => {
        this.list = this.list.filter(item => item.id !== id)
        this.fromList = this.fromList.filter(item => item.fid !== id)
      })
    },
    formatType(row) {
      return this.typeList.find(item => item.id === row.type) ? this.typeList.find(item => item.id === row.type).name : '未知'
    },
    formatDiff(row) {
      return this.diffList.find(item => item.id === row.diff) ? this.diffList.find(item => item.id === row.diff).name : '未知'
    },

    exportQuestion() {
      this.$confirm('确定要导出excel吗').then(() => {
        export_json_to_excel({
          filename: '考试试题',
          header: Object.keys(headers),
          data: this.getExportData(headers)
        })
        this.$message.success('导出成功')
      })
    },
    getExportData(headers) {
      const letters = 'abcdefg'.split('')
      return this.list.map(item => {
        return Object.values(headers).map(value => {
          if (value === 'none') {
            return ''
          } else if (value === 'items') {
            return this.fromList.filter(obj => obj.fid === item.id).map((content, index) => letters[index].toUpperCase() + '.' + content.item).join('~')
          } else if (value === 'diff') {
            return this.diffList.find(o => o.id === item[value]) ? this.diffList.find(o => o.id === item[value]).name : ''
          } else if (value === 'type') {
            return this.typeList.find(o => o.id === item[value]) ? this.typeList.find(o => o.id === item[value]).name : ''
          } else {
            return item[value]
          }
        })
      })
    },
    btnOK() {
      this.$refs.answerForm.validate().then(() => {
        const obj = JSON.parse(JSON.stringify(this.formData))
        if (obj.id) {
          const index = this.list.findIndex(item => item.id === this.formData.id)
          this.list.splice(index, 1, obj)
          const selectItems = ['A', 'B', 'C', 'D', ...this.formItems]
          const childs = selectItems.map(item => {
            return { fid: this.formData.id, id: this.get_uuid(), item: obj[item], name: item }
          })
          const newFrom = this.fromList.filter(item => item.fid !== obj.id)
          newFrom.push(...childs)
          this.fromList = newFrom
          this.currentId = obj.id
        } else {
          const mainId = this.get_uuid()
          this.list.push({ id: mainId, ...obj })
          const selectItems = ['A', 'B', 'C', 'D', ...this.formItems]
          const childs = selectItems.map(item => {
            return { fid: this.formData.id, id: this.get_uuid(), item: obj[item], name: item }
          })
          this.fromList.push(...childs)
          this.currentId = mainId
        }
        this.btnCancel()
      })
    },
    btnCancel() {
      this.formData = {
        title: '',
        A: '',
        B: '',
        C: '',
        D: '',
        answer: '',
        type: '2',
        diff: '3'
      }
      this.$refs.answerForm.resetFields()
      this.showDialog = false
      this.formItems = []
    },
    btnImportOK() {
      if (this.importResult && this.importResult.results) {
        //  处理数据
        const { results } = this.importResult
        const arr = results.slice(this.importNumber - 2)
        const formList = []
        const list = []
        arr.forEach(item => {
          if (item['题干'] && item['题干'].trim()) {
            const mainId = this.get_uuid()
            const items = item['选项'].split('~')
            const arr = 'abcdefghijklmn'.split('')

            const values = {}
            items.forEach((item, index) => {
              values[arr[index].toUpperCase()] = item.substr(2)
            })
            console.log(values)
            const obj = {
              id: mainId,
              title: item['题干'],
              ...values,
              answer: item['答案'] || item['参考答案'],
              'type': this.typeList.find(It => It.name === item['题型']) ? this.typeList.find(It => It.name === item['题型']).id : '',
              'diff': this.diffList.find(It => It.name === item['难度']) ? this.diffList.find(It => It.name === item['难度']).id : ''
            }
            const childs = items.map((item, index) => {
              return { fid: mainId, id: this.get_uuid(), item: item.substr(2), name: arr[index].toUpperCase() }
            })
            formList.push(...childs)
            list.push(obj)
          }
        })
        console.log(list)
        console.log(formList)
        this.$confirm('确定清空原有数据再引入吗？点击取消将追加数据').then(() => {
          this.list = list
          this.fromList = formList
          this.currentId = [0].id
        }).catch(() => {
          this.list.push(...list)
          this.fromList.push(...formList)
        })
        this.importResult = null
        this.showImportDialog = false
      }
    },
    btnImportCancel() {
      this.showImportDialog = false
    }

  }
}
</script>

<style>

</style>
